package study.transaction.atomikos.support.mybatis;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@MapperScan(basePackages = "study.transaction.atomikos.mapper.user",
        sqlSessionFactoryRef = "user_sqlSessionFactory")
@MapperScan(basePackages = "study.transaction.atomikos.mapper.account",
        sqlSessionFactoryRef = "account_sqlSessionFactory")
@Slf4j
@Configuration
public class MybatisConfig {

    @Bean
    public SqlSessionFactory user_sqlSessionFactory(@Qualifier("user_ds") DataSource ds) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        //
        factoryBean.setDataSource(ds);
        //
        MybatisConfiguration configuration = getMybatisConfiguration();
        factoryBean.setConfiguration(configuration);

        GlobalConfig globalConfig = getGlobalConfig();
        factoryBean.setGlobalConfig(globalConfig);
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionFactory account_sqlSessionFactory(@Qualifier("account_ds") DataSource ds) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        //
        factoryBean.setDataSource(ds);
        //
        GlobalConfig globalConfig = getGlobalConfig();
        factoryBean.setGlobalConfig(globalConfig);
        return factoryBean.getObject();
    }

    private MybatisConfiguration getMybatisConfiguration() {
        MybatisConfiguration config = new MybatisConfiguration();
        config.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        config.setJdbcTypeForNull(JdbcType.NULL);
        config.setLogImpl(StdOutImpl.class);
        return config;
    }

    private GlobalConfig getGlobalConfig(){
        //Step-3: mybatis plus全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setBanner(false);
        //db config
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setIdType(IdType.AUTO);
        globalConfig.setDbConfig(dbConfig);
        return globalConfig;
    }
}
